package cn.sciento.boot.api.customize.generator;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import cn.sciento.boot.api.customize.commons.vo.ApiCustomizeRule;
import cn.sciento.boot.api.customize.util.ParamUtil;

public class GroovyCodeGenerator extends AbstractCodeGenerator {
  private static final String TYPE = "GROOVY";
  
  public boolean support(String type) {
    return "GROOVY".equalsIgnoreCase(type);
  }
  
  public String generate(ClassPool classPool, CtClass targetClass, CtMethod targetMethod, ApiCustomizeRule rule, boolean returnValue) {
    StringBuilder builder = new StringBuilder();
    builder
      .append("groovy.lang.Binding binding = new groovy.lang.Binding();")
      .append("\r\n")
      .append("groovy.lang.GroovyShell shell = new groovy.lang.GroovyShell(binding, new org.codehaus.groovy.control.CompilerConfiguration().addCompilationCustomizers(new org.kohsuke.groovy.sandbox.SandboxTransformer()));")
      .append("\r\n")
      
      .append("java.util.Map map = ParamUtil.parseParams(\"").append(ParamUtil.parseParamsKey(targetMethod)).append("\", $args);")
      .append("\r\n")
      .append("for (Object o : map.keySet()) {").append("\r\n")
      .append("binding.setVariable(o.toString(), map.get(o));").append("\r\n")
      .append("}")
      .append("\r\n")
      .append("new NoSystemExitSandbox().register();")
      .append("\r\n")
      .append("new NoRunTimeSandbox().register();")
      .append("\r\n")
      .append("Object object = shell.evaluate(\"").append(ParamUtil.replaceSpecialChar(rule.getTypeValue())).append("\");")
      .append("\r\n");
    if (returnValue)
      builder.append("return ($r) result;").append("\r\n"); 
    return builder.toString();
  }
}
